package com.springsecurity.adminpro.common.security;

import com.springsecurity.adminpro.common.exception.UserCountLockException;
import com.springsecurity.adminpro.entity.SysUser;
import com.springsecurity.adminpro.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 自定义UserDetails
 *
 * @author: Captain
 * @create: 2023-01-30
 **/
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或者密码错误！");
        } else if ("1".equals(user.getStatus())) {
            throw new UserCountLockException("该用户账号已被封禁，具体联系管理员！");
        }

        return new User(user.getUsername(), user.getPassword(), getUserAuthority(user.getId()));
    }


    public List<GrantedAuthority> getUserAuthority(Long userId) {
        String userAuthorityInfo = sysUserService.getUserAuthorityInfo(userId);
        System.out.println("authority=" + userAuthorityInfo);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(userAuthorityInfo);
    }

}
